package com.manage.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class JDBCUtils {

    //创建连接池对象
    private static DataSource dataSource; //连接池(数据源)

    static{
        try {
            //加载配置文件
            Properties properties = new Properties();
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(in);
            dataSource =  DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    public static Connection getConn(){
        Connection conn = tl.get();
        if(conn == null){
            try {
                //从数据源连接池中获取Connection连接对象
                conn = dataSource.getConnection();
                tl.set(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return conn;
    }


    public static void close(ResultSet rs, Statement statement){
        try {
            if(rs != null)
                rs.close();
            if(statement != null)
                statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //事务相关的封装

    public static void begin(){
        Connection conn = getConn();
        try {
            conn.setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void commit(){
        Connection conn = getConn();
        try {
            conn.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                conn.close();//因为conn从数据源连接池中获取到的。所以调用close方法并不是关闭连接，而是归还到连接池
                tl.remove(); //从ThreadLocal中移除Connection对象
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void rollBack(){
        Connection conn = getConn();
        try {
            conn.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                conn.close();//因为conn从数据源连接池中获取到的。所以调用close方法并不是关闭连接，而是归还到连接池
                tl.remove(); //从ThreadLocal中移除Connection对象
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
